package org.jeecg.modules.storage.service.impl;

import org.jeecg.modules.storage.entity.MtStorage;
import org.jeecg.modules.storage.entity.MtStorageItem;
import org.jeecg.modules.storage.mapper.MtStorageItemMapper;
import org.jeecg.modules.storage.mapper.MtStorageMapper;
import org.jeecg.modules.storage.service.IMtStorageService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 库存入库/出库单
 * @Author: cheng
 * @Date:   2023-04-25
 * @Version: V1.0
 */
@Service
public class MtStorageServiceImpl extends ServiceImpl<MtStorageMapper, MtStorage> implements IMtStorageService {

	@Autowired
	private MtStorageMapper mtStorageMapper;
	@Autowired
	private MtStorageItemMapper mtStorageItemMapper;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(MtStorage mtStorage, List<MtStorageItem> mtStorageItemList) {
		mtStorageMapper.insert(mtStorage);
		if(mtStorageItemList!=null && mtStorageItemList.size()>0) {
			for(MtStorageItem entity:mtStorageItemList) {
				//外键设置
				entity.setStorageId(mtStorage.getId());
				mtStorageItemMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(MtStorage mtStorage,List<MtStorageItem> mtStorageItemList) {
		mtStorageMapper.updateById(mtStorage);
		
		//1.先删除子表数据
		mtStorageItemMapper.deleteByMainId(mtStorage.getId());
		
		//2.子表数据重新插入
		if(mtStorageItemList!=null && mtStorageItemList.size()>0) {
			for(MtStorageItem entity:mtStorageItemList) {
				//外键设置
				entity.setStorageId(mtStorage.getId());
				mtStorageItemMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		mtStorageItemMapper.deleteByMainId(id);
		mtStorageMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			mtStorageItemMapper.deleteByMainId(id.toString());
			mtStorageMapper.deleteById(id);
		}
	}
	
}
